package com.amon.canary;

import java.lang.reflect.Field;

public class ReflectUtils {
    public static Object getFiledObject(Object obj, String fieldName) {
        try {
            Field field = getDeclaredField(obj, fieldName);
            if (field == null) {
                return null;
            }
            return field.get(obj);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static Field getDeclaredField(Object obj, String fieldName) {
        Class<?> clazz = obj.getClass();
        while (clazz != Object.class) {
            try {
                Field field = clazz.getDeclaredField(fieldName);
                field.setAccessible(true);
                return field;
            } catch (Exception e) {
                clazz = clazz.getSuperclass();
                e.printStackTrace();
            }
        }
        return null;
    }
}
